package leetcode.primary;

import utils.linkedList.ListNode;

import java.util.HashMap;
import java.util.Map;

public class T160 {
    int count;
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA==null || headB==null){
            System.out.println("headA or headB is null");
            return null;
        }
        ListNode nodeA = getLinkedListLast(headA);
        int lenA = count;
        ListNode nodeB = getLinkedListLast(headB);
        int lenB = count;
        if (nodeA!=nodeB){
            System.out.println("nodeA!=nodeB");
            return null;
        }
        int x = Math.abs(lenA-lenB);
        nodeA = headA;
        nodeB = headB;
        if (lenA<lenB){
            while (x>0){
                nodeB = nodeB.next;
                x--;
            }
        }else {
            while (x>0){
                nodeA = nodeA.next;
                x--;
            }
        }

        while (nodeA!=nodeB){
            nodeA = nodeA.next;
            nodeB = nodeB.next;
        }
        return nodeA;
    }

    public ListNode getLinkedListLast(ListNode node){
        count=1;
        while (node.next!=null){
            node = node.next;
            count++;
        }
        return node;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = null;

        ListNode node6 = new ListNode(6);
        node6.next = node4;

        T160 t160 = new T160();
        ListNode node = t160.getIntersectionNode(node1, node6);
        if (node!=null){
            System.out.println(node.val);
        }

    }
}
